import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { PostItem } from "@src/model";
import {  getSquarePostDetail } from "@src/service";

export interface PostDetailState {
  data: Partial<PostItem>;
  loading: boolean; // 请求数据中
  error: string | null; // 是否错误
}


const initialState: PostDetailState = {
  data: {},
  loading: false,
  error: null,
};


export const getPostDetail = createAsyncThunk<any, number>(
  "post/getPostDetail",
  async (id: number, { rejectWithValue }) => {
    try {
      const response = await getSquarePostDetail(id,{});
      return response.data;
    } catch (error) {
      return rejectWithValue(error);
    }
  }
);


export const PostDetailSlice = createSlice({
  name: "postDetail",
  initialState,
  reducers: {
  },
  extraReducers: {
    [getPostDetail.pending.type]: (state) => {
      state.loading = true;
    },
    [getPostDetail.fulfilled.type]: (state, action) => {
      const { code, message, data } = action.payload;
      if (Object.is(code, 0)) {
        state.loading = false;
        state.data = data;
      } else {
        state.loading = false;
        state.error = message;
      }
    },
    [getPostDetail.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false;
      state.error = action.payload;
    }
  }
});


